package com.cyanite.playlv2;

import com.cyanite.playlv2.util.TabsUtil;
import com.cyanite.playlv2.util.UiUtil;
import com.cyanite.playlv2.util.UserUtils;
import com.cyanite.playlv2.widget.DataBaseAdapter;
import com.cyanite.playlv2api.types.Response;
import com.cyanite.playlv2.R;

import android.app.Activity;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.TabHost;

import java.util.ArrayList;

public class MainActivity extends TabActivity {
    private TabHost mTabHost;

    private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setDefaultKeyMode(Activity.DEFAULT_KEYS_SEARCH_LOCAL);
        registerReceiver(mLoggedOutReceiver, new IntentFilter(PlayLv2.INTENT_ACTION_LOGGED_OUT));
        
        if (((PlayLv2) getApplication()).isFirstRun()) {
            ((PlayLv2) getApplication()).setIsFristRun(false);
            startActivity(new Intent(MainActivity.this, StartPageActivity.class));
            return;
        }
        // Don't start the main activity if we don't have credentials
        if (!((PlayLv2) getApplication()).isReady()) {
            redirectToLoginActivity();
            return;
        }
        PlayLv2 playlv2 = (PlayLv2) getApplication();
        playlv2.getPlayLv2Api().setAuthUserId(playlv2.getUserId());
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.main_activity);
        initTabHost();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mLoggedOutReceiver);
    }

    private void initTabHost() {
        if (mTabHost != null) {
            throw new IllegalStateException("Trying to intialize already initializd TabHost");
        }

        String userId = ((PlayLv2) getApplication()).getUserId();
        String userGender = ((PlayLv2) getApplication()).getUserGender();

        mTabHost = getTabHost();
        TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_trips), R.drawable.tab_main_nav_trips_selector,
                1, new Intent(this, TripActivity.class));

        TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_share), R.drawable.tab_main_nav_tips_selector,
                2, new Intent(this, ShareActivity.class));

        Intent intent = new Intent(this, NearbyVenuesActivity.class);
        intent.putExtra(NearbyVenuesActivity.INTENT_EXTRA_STARTUP_GEOLOC_DELAY, 4000L);
        TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_nearby), R.drawable.tab_main_nav_nearby_selector,
                 3, intent);

        // 'Me' tab, just shows our own info. At this point we should have a
        // stored user id, and a user gender to control the image which is
        // displayed on the tab.
        Intent intentTabMe = new Intent(this, UserDetailsActivity.class);
        intentTabMe.putExtra(UserDetailsActivity.EXTRA_USER_ID, userId == null ? "": userId);
        intentTabMe.putExtra(UserDetailsActivity.EXTRA_MAIN, 1);
        TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_me),
                UserUtils.getDrawableForMeTabByGender(userGender), 4, intentTabMe);

        // Fix layout for 1.5.
        if (UiUtil.sdkVersion() < 4) {
            FrameLayout flTabContent = (FrameLayout)findViewById(android.R.id.tabcontent);
            flTabContent.setPadding(0, 0, 0, 0);
        }
        
        startTaskDBloading(this);
    }

    private void redirectToLoginActivity() {
        setVisible(false);
        Intent intent = new Intent(this, LoginActivity.class);
        intent.setAction(Intent.ACTION_MAIN);
        intent.setFlags(
            Intent.FLAG_ACTIVITY_NO_HISTORY |
            Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
            Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }
    
    private void DBloadingTaskComplete(ArrayList<String> mDBlist, Response response) {
        if (response != null)   {
            ((PlayLv2) getApplication()).setDBList(mDBlist);
        }
    }
    
    private static class DBloadingTask extends AsyncTask<Void, Void, Response> {
        private MainActivity mActivity;
        private ArrayList<String> mDBlist;
        
        public DBloadingTask(MainActivity activity) {
            mActivity = activity;
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected Response doInBackground(Void... params) {
            DataBaseAdapter db = new DataBaseAdapter(mActivity);
            try   {
                db.open();
                mDBlist = new ArrayList<String>();
                db.getCityList(mDBlist);
                db.getPlacesList(mDBlist);
                db.close();
                return new Response();
            }
            catch(Exception ex) {
                return null;
            }            
        }

        @Override
        protected void onPostExecute(Response response) {
            if (mActivity != null) {
                mActivity.DBloadingTaskComplete(mDBlist, response);
            }
        }
    }
    
    public void startTaskDBloading(MainActivity activity) {
        DBloadingTask task = new DBloadingTask(activity);
        task.execute();
    }        
}
